package com.bd.wechat.controller;

import com.bd.wechat.config.MinioConfig;
import com.bd.wechat.core.R;
import com.bd.wechat.entity.FileUpload;
import com.bd.wechat.service.FileService;
import com.bd.wechat.utils.FileCheckUtils;
import com.bd.wechat.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @menu 小程序端
 */
@Slf4j
@RestController
@RequestMapping("/wechat")
public class FileController {
    @Resource
    private FileService fileService;
    @Resource
    private MinioConfig minioConfig;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("upload")
    public R<FileUpload> upload(MultipartFile file) {
        try {
            //先做一个校验
            if (FileCheckUtils.checkMediaType(file)) {
                // 上传并返回访问地址
                String url = fileService.uploadFile(file);
                FileUpload fileUpload = new FileUpload();
                fileUpload.setName(FileUtils.getName(url));
                fileUpload.setUrl(url);
                return R.ok(fileUpload);
            } else {
                return R.fail("文件类型异常，请上传图片或视频!");
            }
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail("文件上传失败");
        }
    }

    /**
     * 文件下载
     *
     * @param bucketName
     * @param objectName
     * @param response
     * @return
     */
    @GetMapping("/download")
    public void downloadImage(String bucketName, String objectName, HttpServletResponse response) throws Exception {
        fileService.download(bucketName, objectName, response);
    }
}
